<?php
//$Id: Cache.php 603 2012-12-14 07:55:57Z tomqin@gmail.com $

/**
 * Part of the framework.
 *
 * @package     Library
 * @version     1.0
 * @copyright   Copyright (C) 2010-2012 SupeFun.com Inc.
 * @author      TomQin <tomqin@gmail.com>
 * @license     http://www.supefun.com/license/
 */

final Class Cache
{
    private static $cache;

    /**
     * 读取一个文本类的缓存
     *
     * @param  string   缓存名称
     * @param  int      缓存时间（秒），0或负值则为永久缓存
     * @return mixed    缓存值
     */
    public static function read($name, $cache_time = 0) {
        $key = md5($name);
        if(!isset(self::$cache[$key])){
            self::$cache[$key] = self::_get_cache($key, $cache_time);
        }
        return self::$cache[$key];
    }

    /**
     * 保存一个文本类的缓存
     *
     * @param  string   缓存名称
     * @param  mixed    缓存值
     * @return bool
     */
    public static function write($name, $content) {
        $key = md5($name);
        $file = self::_cache_file($key);
        $dir  = dirname($file);
        if(!is_dir($dir))
            mkdir($dir, 0777, true);
        return file_put_contents($file, $content);
    }

    /**
     * 取得一个数据类的缓存
     *
     * @param  string   缓存名称
     * @param  int      缓存时间（秒），0或负值则为永久缓存
     * @return mixed    缓存值
     */
    public static function get($key, $cache_time = 0) {
        if(!isset(self::$cache[$key])){
            $data = self::_get_cache($key, $cache_time);
            if($data){
                $data = @unserialize($data);
            }
            self::$cache[$key] = $data ? $data : null;
        }
        return self::$cache[$key];
    }

    /**
     * 设置一个数据类的缓存
     *
     * @param  string   缓存名称
     * @param  mixed    缓存值
     * @return bool
     */
    public static function set($key, $data) {
        $file = self::_cache_file($key);
        $dir  = dirname($file);
        if(!is_dir($dir))
            mkdir($dir, 0777, true);
        return file_put_contents($file, serialize($data));
    }

    private static function _get_cache($key, $cache_time = 0) {
        $file = self::_cache_file($key);
        if(!is_file($file)){
            return null;
        }
        if($cache_time && TIMESTAMP - filemtime($file) > $cache_time) {
            return null;
        }else{
            if(is_file($file)){
                return file_get_contents($file);
            }else{
                return null;
            }
        }
    }

    private static function _cache_file($key) {
        if(strlen($key) == 32){//对应 read/write
            return DATA_PATH . 'cache' .DS. $key{0} .DS. $key{1} .DS. $key{2} .DS. $key.'.dat';
        }else{ //get/set
            return DATA_PATH . 'cache' .DS. $key . '.dat';
        }
    }
}
